package com.kunya.product.service.impl;

import com.kunya.common.common.ServerResponse;
import com.kunya.product.dao.ServerInfomationMapper;
import com.kunya.product.po.ServerInfomation;
import com.kunya.product.service.IServerInfomationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("iServerInfomationService")
public class ServerInfomationServiceImpl implements IServerInfomationService{


    @Autowired
    private ServerInfomationMapper serverInfomationMapper;

    /**
     * 显示商家信息
     * @param userId
     * @return
     */
    @Override
    public ServerResponse  select(Long userId){
        if (userId == null){
            return ServerResponse.createByErrorMessage("userId不能为空!");
        }
        try {
            return ServerResponse.createBySuccess(serverInfomationMapper.selectByUserId(userId));
        }catch (Exception e){
            return ServerResponse.createBySuccessMessage("查询失败");
        }
    }

    /**
     * 添加或修改商家的信息
     * @param serverInfomation
     * @return
     */
    @Override
    public ServerResponse addOrUpdate(ServerInfomation serverInfomation){
        if (StringUtils.isEmpty(serverInfomation.getUserId().toString())){
            return ServerResponse.createByErrorMessage("userId不能为空!");
        }
        if (StringUtils.isEmpty(serverInfomation.getSimpleAddress())){
            return ServerResponse.createByErrorMessage("simpleAddress不能为空!");
       }
        if (StringUtils.isEmpty(serverInfomation.getDetailAddress())){
            return ServerResponse.createByErrorMessage("detailAddress不能为空!");
        }
        if (StringUtils.isEmpty(serverInfomation.getPhoneNumber())){
            return ServerResponse.createByErrorMessage("phoneNumber不能为空!");
        }
        if (serverInfomation.getPhoneNumber().length() != 11){
            return ServerResponse.createByErrorMessage("phoneNumber必须是11位!");
        }

        /**
         * 如果有相关信息就更新商家信息
         * 否则添加商家信息
         */
        try {
            Map<String,Object> map = serverInfomationMapper.selectByUserId(serverInfomation.getUserId().longValue());

            serverInfomation.setId(Integer.valueOf(map.get("id").toString()));
            if(serverInfomationMapper.selectByUserId(serverInfomation.getUserId().longValue()) == null){
                serverInfomationMapper.insertSelective(serverInfomation);
            }else{
                serverInfomationMapper.updateByPrimaryKeySelective(serverInfomation);
            }
            return ServerResponse.createBySuccessMessage("操作成功!");
        }catch (Exception e){
            return ServerResponse.createByErrorMessage("操作失败!");
        }
    }
}
